<template>
  <view class="container">
    <!-- 基础信息 -->
    <OrderBasicInfo :dict="dictEnums" :info="orderDetail" />
    <!-- 续租时间选择 -->
    <RenewedTime
      ref="renewedTimeRef"
      :queryPriceParam="queryPriceParam"
      @selectTime="$refs.timePickerSingleRef.open"
    />
    <template v-if="renewalPriceDetail">
      <!-- 取消政策 -->
      <CancelRule :dict="dictEnums" :car_use_time="queryPriceParam.carUseTime" :info="renewalPriceDetail.cancel_strategy_struct" />
      <!-- 增值服务 -->
      <AddService :dict="dictEnums" :info="renewalPriceDetail.added_service_list" />
    </template>
    <!-- 底部按钮 可用状态展示 -->
    <bottom-box>
      <view class="payment-block">
        <view class="price">
          <text class="label">订单金额：</text>
          <text class="icon">¥</text>
          <text class="num">{{ sumFee }}</text>
        </view>
        <template v-if="renewalPriceDetail">
          <view class="n-price-detail" @click="onExpenseDetailClick">
            <view>明细</view>
            <u-icon name="arrow-up" color="#2F86F6" size="18"></u-icon>
          </view>
          <view class="btn" @click="onConfirmClick">
            <text>确认下单</text>
          </view>  
        </template>
        <template v-else>
          <view class="btn disabled">
            <text>请先选择续租结束时间</text>
          </view>  
        </template>
      </view>
    </bottom-box>
    <!-- 费用明细 -->
    <expenseDetails ref="expenseRef" :info="renewalPriceDetail"></expenseDetails>
    <!-- toast -->
    <u-toast ref="uToast" />
    <!-- 时间选择器 -->
    <TimePickerSingle
      title="请选择续租结束时间"
      ref="timePickerSingleRef"
      @confirm="onTimePickerSingleConfirm"
    />
  </view>
</template>
<script>
import OrderBasicInfo from "./compnoents/renewed/basicInfo.vue";
import RenewedTime from "./compnoents/renewed/renewedTime.vue";
import TimePickerSingle from "@/components/time-picker-single/index.vue";
import CancelRule from "./compnoents/itemDetail/cancelRule.vue";
import AddService from "./compnoents/itemDetail/addService.vue";
import BottomBox from "@/components/bottom-box/bottom-box.vue";
import ExpenseDetails from "./compnoents/itemDetail/expenseDetails.vue";
import {
  getEnums,
  fliggyOrderDetail,
  fliggyRenewalPriceQuery,
  fliggyRenewalOrderCreate,
} from "@/api/user";
import decimal from "@/utils/calculation.js";

export default {
  data() {
    return {
      orderDetail: {},
      dictEnums: {},

      // 查询续租报价 param
      queryPriceParam: {
        orderId: null,
        carUseTime: null,
        carReturnTime: null,
      },
      // 续租报价信息
      renewalPriceDetail: null,
    };
  },
  components: {
    OrderBasicInfo,
    RenewedTime,
    TimePickerSingle,
    CancelRule,
    AddService,
    ExpenseDetails,
  },
  created() {
    // 获取页面枚举
    getEnums().then((res) => {
      if (res.code == 200) {
        const result = res.result;
        this.dictEnums = result;
      }
    });
  },
  computed: {
    // 选中的增值服务费
    checkedAddedServiceList() {
      if (this.renewalPriceDetail) {
        let added_service_list = this.renewalPriceDetail.added_service_list || [];
        return added_service_list.filter((item) => item.checked);
      } else {
        return []
      }
    },
    sumFee() {
      if (this.renewalPriceDetail) {
        const totalFee = this.renewalPriceDetail.price_info.total_fee || 0;
        let sum = totalFee;
        // 增值服务费
        this.checkedAddedServiceList.forEach((item) => {
          sum = decimal.add(sum, item.service_price_amount || 0);
        });
        return Number(sum).toFixed(2);
      } else {
        return '0.00'
      }
    },
  },
  methods: {
    // 日期选择确认
    onTimePickerSingleConfirm(value) {
      this.queryPriceParam.carReturnTime = value;
      this.queryPrice();
    },
    // 获取续租报价
    queryPrice() {
      fliggyRenewalPriceQuery(this.queryPriceParam).then((res) => {
        if (res.code == 200) {
          const result = res.result;
          this.renewalPriceDetail = result
        } else {
          this.renewalPriceDetail = null
        }
      });
    },
    // 费用明细
    onExpenseDetailClick() {
      this.$refs.expenseRef.open();
    },
    // 确认下单
    async onConfirmClick() {
      const priceInfo = this.renewalPriceDetail.price_info;
      // 选中的增值服务
      const sidList = this.checkedAddedServiceList.map((item) => item.sid);
      const param = {
        itemId: this.renewalPriceDetail.item_id,
        refOrderId: this.queryPriceParam.orderId,
        // 选择的增值服务
        selectAddServices: sidList.join(","),
        totalAmount: this.sumFee,
        payAmount: this.sumFee,
        // 优惠政策
        promotionList: priceInfo.promotion_info
          ? [priceInfo.promotion_info]
          : [],
        carUseTime: this.queryPriceParam.carUseTime,
        // 续租结束时间
        carReturnTime: this.queryPriceParam.carReturnTime,
      };
      console.log(param)
      const res = await fliggyRenewalOrderCreate(param);
      if (res.code == 200) {
        uni.reLaunch({
          url: `/pages/renewedSuccess`,
        });
      }
    },
  },
  onLoad(options) {
    const orderId = options.orderId;
    this.channelOrderCode = options.channelOrderCode;
    this.queryPriceParam.orderId = orderId;
    fliggyOrderDetail({ id: orderId }).then((res) => {
      const result = res.result;
      this.orderDetail = result;
      // 续租开始时间，上一次续租结束时间或者订单预计结束时间
      const carUseTime = result.renewalEndTime || result.endTime;
      this.queryPriceParam.carUseTime = carUseTime;
      // 初始化 timePickerSingle
      this.$refs.timePickerSingleRef.init(this.queryPriceParam.carUseTime);
    });
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f9fafd;
  padding: 32rpx;
  padding-top: 0;
  .gap {
    height: 16rpx;
    width: 100%;
  }
}

::v-deep .ve-bottom-box-wrap {
  z-index: 99 !important;
}
::v-deep .ve-bottom-box-wrap-content {
  padding-top: 0 !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
}
.payment-block {
  position: relative;
  box-shadow: 0 -20rpx 20rpx 0 rgba(209, 212, 223, 0.1);
  .num {
    color: #fc5042;
  }
  .priceInfo {
    white-space: nowrap;
    position: absolute;
    color: #909399;
    font-size: 22rpx;
    bottom: 0;
    left: 30rpx;
  }
  .n-price-detail {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    color: #2f86f6;
    font-size: 28rpx;
    top: 30rpx;
    left: 420rpx;
    view:nth-child(1) {
      margin-right: 12rpx;
    }
  }
  .btn.disabled {
    width: auto;
    padding-left: 16rpx;
    padding-right: 16rpx;
    background: linear-gradient(315deg, #b1b2b7 0%, #a5a6ab 100%);
    cursor: no-drop;
  }
}
.clear-icon {
  margin-top: 4px;
  margin-left: 6px;
}
</style>
